package com.samuel.basics.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.samuel.basics.cache.MybatisRedisCache;
import com.samuel.basics.entity.UserEntity;
import org.apache.ibatis.annotations.*;

import java.util.Set;

/**
 * <p>
 * 用户表 Mapper 接口
 * </p>
 *
 * @author kaiji
 * @since 2019-08-17
 */
@Mapper
@CacheNamespace(implementation= MybatisRedisCache.class, eviction= MybatisRedisCache.class)
public interface UserMapper extends BaseMapper<UserEntity> {

    /**
     * <p>
     * 根据电话号码查询这个用户下的角色代码code列表
     * </p>
     * @param phone
     *      手机号码
     * @return
     *      角色代码
     */
    @Select("<script>select b.code from t_user as a, t_role as b, t_user_role as c " +
            "where a.id = c.user_id and b.id = c.role_id and a.phone = #{phone}</script>")
    Set<String> getRoleByPhone(@Param("phone") String phone);

    /**
     * 查询手机号是否存在, id 可以为空！
     *
     * @param id
     *      用户主键
     * @param phone
     *      手机号码
     * @return
     *      用户对象
     */
    @Select("<script>select a.* from t_user as a where a.phone = #{phone} " +
            "<if test='id != null'>" +
            "and a.id != #{id}" +
            "</if></script>")
    UserEntity getUserByExist(@Param("id") String id, @Param("phone") String phone);

    /**
     * 根据用户ID删除角色与用户的关系
     *
     * @param userId
     *      用户ID
     */
    @Delete("<script>delete from t_user_role where user_id = #{userId}</script>")
    @Options(flushCache = Options.FlushCachePolicy.TRUE)
    void deleteRoleByUserId(@Param("userId") String userId);

    @SelectKey(keyProperty = "id",resultType = String.class, before = true,
            statement = "select replace(uuid(), '-', '')")
    @Options(keyProperty = "id", useGeneratedKeys = true, flushCache = Options.FlushCachePolicy.TRUE)
    @Insert("<script>insert into t_user_role(id, user_id, role_id, create_date) values " +
            "(#{id}, #{userId}, #{roleId}, now()) </script>")
    void saveUserAndRole(@Param("userId") String userId, @Param("roleId") String roleId);
}
